﻿using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ImageHandler
{
    public static class ImageHelper
    {
        public static string ConvertToGrayImage(string path)
        {
            string newFileName = $"{Path.GetFileNameWithoutExtension(path)}_gray{Path.GetExtension(path)}";
            string newPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, newFileName);
            Mat img = Cv2.ImRead(path);

            Mat hsv = new Mat();
            Cv2.CvtColor(img, hsv, ColorConversionCodes.BGR2HSV);
            hsv.SaveImage(newPath);
            return newPath;
        }

        public static string Test2(string path)
        {
            string newFileName = $"{Path.GetFileNameWithoutExtension(path)}_2{Path.GetExtension(path)}";
            string newPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, newFileName);

            using var src = new Mat(path, ImreadModes.Color);
            Mat dstImage = ToolsFindContours(src);
            dstImage.SaveImage(newPath);
            return newPath;
        }

        public static Mat ToolsFindContours(Mat srcImage)
        {
            // 转化为灰度图
            Mat src_gray = new Mat();
            Cv2.CvtColor(srcImage, src_gray, ColorConversionCodes.RGB2GRAY);
            // 滤波
            Cv2.Blur(src_gray, src_gray, new OpenCvSharp.Size(9, 9));
            // Canny边缘检测
            Mat canny_Image = new Mat();
            // 输入、输出、最小阀值、最大阀值
            Cv2.Canny(src_gray, canny_Image, 100, 200);
            // 获得轮廓
            OpenCvSharp.Point[][] contours;
            HierarchyIndex[] hierarchly;
            /*
            1.寻找轮廓的图像
            2.返回轮廓数组
            3.层次结构索引
            4.轮廓的检索模式(External只检测外轮廓，List检测所有轮廓，CComp检测所有轮廓并建立两个等级，Tree检测所有轮廓并建立等级树
            5.轮廓近似模式(ApproxNone保存物体边界上所有连续的轮廓点, ApproxSimple仅保存轮廓的拐点信息。CV_CHAIN_APPROX_TC89_L1，CV_CHAIN_APPROX_TC89_KCOS使用Teh-Chin chain 近似算法)
            6.Point偏移量，所有的轮廓信息相对于原始图像对应点的偏移量
            */
            Cv2.FindContours(canny_Image, out contours, out hierarchly, RetrievalModes.Tree, ContourApproximationModes.ApproxNone, new OpenCvSharp.Point(0, 0));
            // 将结果画出并返回结果
            Mat dst_Image = Mat.Zeros(canny_Image.Size(), srcImage.Type());
            for (int i = 0; i < contours.Length; i++)
            {
                // 轮廓的颜色为绿色
                Scalar color = new Scalar(0, 255, 0);
                /*
                1.输入图
                2.表示输入的轮廓组
                3.指明画第几个轮廓
                4.颜色
                5.thickness为轮廓的线宽，如果为负值或CV_FILLED表示填充轮廓内部
                6.线形
                7.轮廓结构信息
                */
                Cv2.DrawContours(dst_Image, contours, i, color, 2, LineTypes.Link8, hierarchly);
            }
            return dst_Image;
        }
    }
}
